<template>
    <div class="oj-navbar">
      <div class="oj-navbar-menus">
        <img class="oj-navbar-logo" src="@/assets/logo.png" />
        <el-menu router class="oj-navbar-menu" mode="horizontal">
          <el-menu-item index="/c-oj/home/question">题库</el-menu-item>
          <el-menu-item index="/c-oj/home/exam">竞赛</el-menu-item>
        </el-menu>
      </div>
      <div class="oj-navbar-users">
        <img v-if="isLogin" class="oj-message-icon" src="@/assets/message/message.png" alt="message" @click="goToMessage" />
        <el-dropdown v-if="isLogin" @command="handleCommand">
          <img class="oj-message" :src="userInfo.headImage || '@/assets/user/head_image.png'" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="userDetail">个人中心</el-dropdown-item>
              <el-dropdown-item command="myExam">我的竞赛</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <span class="oj-navbar-login-btn" v-if="!isLogin" @click="goLogin">登录</span>
      </div>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref, onMounted } from 'vue';
  import router from '@/router';
  import { getToken, removeToken } from '@/utils/cookie';
  import { logoutService, getUserInfoService, getUserDetailService } from '@/apis/user';
  import { useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  
  const route = useRoute();
  const isLogin = ref(false)
  const userInfo = reactive({
    nickName: '',
    headImage: ''
  })
  
  async function checkLogin() {
    if (getToken()) {
      try {
        const userInfoRes = await getUserInfoService()
        Object.assign(userInfo, userInfoRes.data)
        isLogin.value = true
        // 获取用户头像
        const userDetailRes = await getUserDetailService()
        if (userDetailRes.data.headImage) {
          userInfo.headImage = userDetailRes.data.headImage
        }
      } catch (error) {
        console.error('获取用户信息失败：', error)
        isLogin.value = false
        removeToken()
      }
    } else {
      isLogin.value = false
    }
  }
  
  // 改为在组件挂载时检查登录状态
  onMounted(() => {
    checkLogin();
  });
  
  // 监听路由变化，当路由变化时重新检查登录状态
  router.afterEach((to) => {
    // 如果路由变化且不是首页、题库页面或竞赛页面，则重新请求用户信息
    if (to.path !== '/c-oj/home' && to.path !== '/c-oj/home/question' && to.path !== '/c-oj/home/exam' && getToken()) {
      getUserInfoService().then(res => {
        Object.assign(userInfo, res.data);
        isLogin.value = true;
        // 获取用户头像
        getUserDetailService().then(detailRes => {
          if (detailRes.data.headImage) {
            userInfo.headImage = detailRes.data.headImage
          }
        });
      });
    }
  });
  
  function goLogin() {
    router.push('/c-oj/login')
  }
  
  function goToMessage() {
    router.push('/c-oj/home/user/message')
  }
  
  function goMyExam() {
    router.push('/c-oj/home/user/exam')
  }
  
  function handleCommand(command) {
    switch (command) {
      case 'userDetail':
        router.push('/c-oj/home/user/detail').then(() => {
          window.location.reload()
        })
        break
      case 'myExam':
        router.push('/c-oj/home/user/exam')
        break
      case 'logout':
        handleLogout()
        break
    }
  }
  
  async function handleLogout() {
    try {
      await ElMessageBox.confirm(
        '确定要退出登录吗？',
        '退出提示',
        {
          confirmButtonText: '确认退出',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'custom-message-box',
          confirmButtonClass: 'custom-confirm-button',
          cancelButtonClass: 'custom-cancel-button',
          distinguishCancelAndClose: true,
          center: true,
          showClose: true,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        }
      )
      await logoutService()
      removeToken()
      isLogin.value = false
      ElMessage.success('退出登录成功')
    } catch (error) {
      if (error !== 'cancel' && error !== 'close') {
        ElMessage.error('退出登录失败，请重试')
      }
    }
  }
  
  
  </script>
  
  <style lang="scss" scoped>
  .oj-navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    box-sizing: border-box;
  
    max-width: 1520px;
    margin: 0 auto;
  
    .oj-navbar-menus {
      display: flex;
      align-items: center;
      height: 50px;
  
      .el-menu-item {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 20px;
        color: #222222;
        line-height: 28px;
        text-align: center;
        width: 42px;
        text-align: left;
        margin-right: 25px;
      }
    }
  
    .oj-navbar-logo {
      width: 38px;
      height: 38px;
      background: #32C5FF;
      border-radius: 8px;
      cursor: pointer;
      object-fit: contain;
      margin-right: 59px;
    }
  
    .oj-navbar-menu {
      // margin-left: 18px;
      width: 600px;
      border: none;
  
      .el-menu-item {
        font-size: 16px;
        font-weight: 500;
        background-color: transparent !important;
        transition: none;
        border: none;
        line-height: 60px;
      }
    }
  
    .oj-navbar-users {
      display: flex;
      align-items: center;
      gap: 20px;

      .oj-message-icon {
        width: 24px;
        height: 24px;
        cursor: pointer;
        transition: transform 0.2s;
        &:hover {
          transform: scale(1.1);
        }
      }
    }
  
    .oj-navbar-login-btn {
      line-height: 60px;
      display: inline-block;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #32C5FF;
      text-align: center;
      cursor: pointer;
      padding: 0 16px;
      border-radius: 6px;
      transition: background 0.2s;
      &:hover {
        background: #e6f7ff;
      }
    }
  
    .oj-message {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      cursor: pointer;
      object-fit: cover;
      transition: transform 0.2s;
      &:hover {
        transform: scale(1.05);
      }
    }
  }
  </style>

  <style lang="scss">
  .custom-message-box {
    width: 400px !important;
    background: #fff !important;
    border-radius: 8px !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    z-index: 9999 !important;
    
    .el-message-box__header {
      padding: 20px !important;
      border-bottom: 1px solid #f0f0f0 !important;
      position: relative !important;
      
      .el-message-box__title {
        font-size: 16px !important;
        font-weight: 500 !important;
        color: #333 !important;
        text-align: center !important;
      }
      
      .el-message-box__headerbtn {
        position: absolute !important;
        top: 12px !important;
        right: 12px !important;
        padding: 0 !important;
        background: transparent !important;
        border: none !important;
        outline: none !important;
        cursor: pointer !important;
        font-size: 16px !important;
        color: #909399 !important;
        
        &:hover {
          color: #32C5FF !important;
        }
      }
    }
    
    .el-message-box__content {
      padding: 30px 20px !important;
      font-size: 14px !important;
      color: #666 !important;
      text-align: center !important;
    }
    
    .el-message-box__btns {
      padding: 0 20px 20px !important;
      text-align: center !important;
      
      .custom-confirm-button {
        background: #32C5FF !important;
        border-color: #32C5FF !important;
        color: white !important;
        font-size: 14px !important;
        padding: 8px 20px !important;
        border-radius: 4px !important;
        margin-left: 10px !important;
        
        &:hover {
          background: #1ab0e6 !important;
          border-color: #1ab0e6 !important;
        }
      }
      
      .custom-cancel-button {
        background: #fff !important;
        border-color: #dcdfe6 !important;
        color: #606266 !important;
        font-size: 14px !important;
        padding: 8px 20px !important;
        border-radius: 4px !important;
        
        &:hover {
          color: #32C5FF !important;
          border-color: #c6e2ff !important;
          background-color: #ecf5ff !important;
        }
      }
    }
  }
  </style>